package com.wangziyu.facerecognitiongate.task

import android.util.Log
import com.wangziyu.facerecognitiongate.task.base.Task
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * @description 任务管理器，负责启动和取消所有任务
 * @author wzy
 * @date 2025/08/10 02:32:33
 */
class TaskManager constructor(private val scope: CoroutineScope) {
    companion object {
        const val TAG = "TaskManager"
    }

    private val tasks = mutableListOf<Task>()
    private val jobMap = mutableMapOf<String, Job>()

    fun addTask(task: Task) {
        tasks.add(task)
    }

    fun startAll() {
        tasks.forEach { task ->
            if (jobMap[task.name]?.isActive == true) {
                Log.i(TAG, "任务${task.name}已在运行")
                return@forEach
            }
            val job = scope.launch {
                try {
                    Log.i(TAG, "启动任务：${task.name}")
                    task.execute()
                } catch (e: Exception) {
                    Log.i(TAG, "任务${task.name}执行异常: ${e.message}")
                }
            }
            jobMap[task.name] = job
        }
    }

    fun cancelAll() {
        jobMap.values.forEach { it.cancel() }
        jobMap.clear()
    }
}